package com.amado.easyui2.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.amado.easyui2.constant.GlobalConstants;
import com.amado.easyui2.domain.DrivingSchoolEntity;
import com.amado.easyui2.service.DrivingSchoolService;
import com.amado.easyui2.service.impl.DrivingSchoolServiceImpl;
import com.amado.easyui2.util.JsonUtil;
import com.amado.easyui2.vo.Page;
import com.fasterxml.jackson.databind.ObjectMapper;

public class DrivingSchoolServlet extends HttpServlet {
	private DrivingSchoolService drivingSchoolService = new DrivingSchoolServiceImpl();
	private static ObjectMapper mapper = new ObjectMapper();
	private static final long serialVersionUID = 1L;

	@Override
	protected void service(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException {
		arg0.setCharacterEncoding("UTF-8");
		arg1.setCharacterEncoding("UTF-8");
		String method = arg0.getParameter("method");
		if ("add".equals(method)) {
			add(arg0, arg1);
		} else if ("delete".equals(method)) {
			delete(arg0, arg1);
		} else if ("update".equals(method)) {
			update(arg0, arg1);
		} else if ("edit".equals(method)) {
			edit(arg0, arg1);
		} else if ("query".equals(method)) {
			query(arg0, arg1);
		} else if ("login".equals(method)) {
			login(arg0, arg1);
		}
	}

	private void delete(HttpServletRequest arg0, HttpServletResponse arg1) throws IOException {
		PrintWriter out = arg1.getWriter();
		try {
			String ids = arg0.getParameter("ids");
			if (ids != null) {
				String[] idAray = ids.split(",");
				if (idAray.length > 5) {
					out.print(mapper.writeValueAsString(new Result("2", "删除数据不能超过5个")));
				} else {
					List<Long> idList = new ArrayList<>();
					for (String tempId : idAray) {
						// idList.add(Long.valueOf(Long.parseLong(tempId)));
						// idList.add(Long.parseLong(tempId));
						idList.add(Long.valueOf(tempId));
					}
					drivingSchoolService.delete(idList);
					// 1:成功
					out.print(mapper.writeValueAsString(new Result()));
				}
			}
		} catch (Exception e) {
			out.print(mapper.writeValueAsString(new Result("2", e.getMessage())));
		}
	}

	private void add(HttpServletRequest arg0, HttpServletResponse arg1) {
		String strJson = arg0.getParameter("data");
		DrivingSchoolEntity userInfo = JsonUtil.jsonToBean(strJson, DrivingSchoolEntity.class);
		drivingSchoolService.add(userInfo);

	}

	class Result {
		// 0失败，1成功
		private String resultCode = "1";
		private String resultMessage = "成功";

		public Result() {
		}

		public Result(String resultCode, String resultMessage) {
			super();
			this.resultCode = resultCode;
			this.resultMessage = resultMessage;
		}

		public String getResultCode() {
			return resultCode;
		}

		public void setResultCode(String resultCode) {
			this.resultCode = resultCode;
		}

		public String getResultMessage() {
			return resultMessage;
		}

		public void setResultMessage(String resultMessage) {
			this.resultMessage = resultMessage;
		}
	}

	private void update(HttpServletRequest arg0, HttpServletResponse arg1) {
		String strJson = arg0.getParameter("data");
		DrivingSchoolEntity drivingInfo = JsonUtil.jsonToBean(strJson, DrivingSchoolEntity.class);
		Long id = drivingInfo.getId();
		String drivingSchoolName = drivingInfo.getDrivingSchoolName();
		String companyName = drivingInfo.getCompanyName();
		String validTime = drivingInfo.getValidTime();
		String serviceCode = drivingInfo.getServiceCode();
		String abbreviation = drivingInfo.getAbbreviation();
		String bhName = drivingInfo.getBhName();
		String blNumber = drivingInfo.getBlNumber();
		Date blValidTime = drivingInfo.getBlValidTime();
		String bhFirstSolar = drivingInfo.getBhFirstSolar();
		String area = drivingInfo.getArea();
		String licenseNo = drivingInfo.getLicenseNo();
		String site = drivingInfo.getSite();
		String postalCode = drivingInfo.getPostalCode();
		String businessScope = drivingInfo.getBusinessScope();
		String fn = drivingInfo.getFn();
		String legalPerson = drivingInfo.getLegalPerson();
		String phone = drivingInfo.getPhone();
		String registerSerialNumber = drivingInfo.getRegisterSerialNumber();
		String approvalUnit=drivingInfo.getApprovalUnit();
		String trafficApprovalNumber=drivingInfo.getTrafficApprovalNumber();
		Date approvalDay=drivingInfo.getApprovalDay();
		String bhPopedom=drivingInfo.getBhPopedom();
		String economicNature=drivingInfo.getEconomicNature();
		String deleteLogo=drivingInfo.getDeleteLogo();
		Date createTime=drivingInfo.getCreateTime();
		Date updateTime=drivingInfo.getUpdateTime();
		String createName=drivingInfo.getCreateName();
		String updateName=drivingInfo.getUpdateName();
		DrivingSchoolEntity driving = new DrivingSchoolEntity(id, drivingSchoolName, companyName, validTime, serviceCode,
				abbreviation, bhName, blNumber, blValidTime,bhFirstSolar,  area, licenseNo, site, postalCode,
				businessScope, fn, legalPerson, phone, registerSerialNumber,approvalUnit,trafficApprovalNumber,approvalDay,bhPopedom,economicNature,deleteLogo,
				createTime,updateTime,createName,updateName);
		drivingSchoolService.update(driving);
	}

	private void edit(HttpServletRequest arg0, HttpServletResponse arg1) throws IOException {
		Long id = Long.valueOf(arg0.getParameter("id"));
		List<DrivingSchoolEntity> list = drivingSchoolService.list();
		for (DrivingSchoolEntity driving : list) {
			if (driving.getId().equals(id)) {
				DrivingSchoolEntity coachId = driving;
				PrintWriter out = arg1.getWriter();
				out.print(mapper.writeValueAsString(coachId));
				break;
			}
		}

	}

	private void query(HttpServletRequest arg0, HttpServletResponse arg1) throws IOException {
		Page page = new Page();
		String strPage = arg0.getParameter("page");
		String strRows = arg0.getParameter("rows");
		int page1 = strPage == null ? 1 : Integer.parseInt(strPage);//
		int rows = strRows == null ? 5 : Integer.parseInt(strRows);
		String cn = arg0.getParameter("cn");
		String bln = arg0.getParameter("bln");
		page.setCurrentPage(page1);
		page.setRowSize(rows);
		Page<DrivingSchoolEntity> pageList = drivingSchoolService.listAll(cn, bln, page);
		PrintWriter out = arg1.getWriter();
		out.print(mapper.writeValueAsString(pageList));

	}

	private void login(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException {
		String companyName = arg0.getParameter("companyName");
		String blNumber = arg0.getParameter("blNumber");
		DrivingSchoolEntity drivingInfo = new DrivingSchoolEntity(companyName, blNumber);
		String verifyCode = arg0.getParameter("VerificationCode");
		String sessionVerifyCode = (String) arg0.getSession(true).getAttribute(verifyCode);
		if (sessionVerifyCode != null && sessionVerifyCode.equals(verifyCode)) {
			arg0.getRequestDispatcher("login.jsp").forward(arg0, arg1);
			return;
		}
		List<DrivingSchoolEntity> list = drivingSchoolService.getCoach(drivingInfo);
		if (list != null) {
			list.forEach(e -> {
				if (e.getCompanyName() != null && !e.getCompanyName().equals("") && e.getBhName() != null
						&& !e.getBhName().equals("")) {
					arg0.getSession().setAttribute(GlobalConstants.SESSION_USER, companyName);
					try {
						arg1.sendRedirect("index.jsp");
					} catch (IOException e1) {
						e1.printStackTrace();
					}
				} else {
					arg0.setAttribute("msg", "用户名或密码错误");
					try {
						arg0.getRequestDispatcher("login.jsp").forward(arg0, arg1);
					} catch (ServletException e1) {
						e1.printStackTrace();
					} catch (IOException e1) {
						e1.printStackTrace();
					}
				}
			});
		}
	}

}
